package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.exception.CustException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;


@Service
public class ApBehaviorEntryServiceImpl implements ApBehaviorEntryService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public ApBehaviorEntry findByUserIdOrEquipmentId(Integer userId, Integer equipmentId) {
        // 1 判断userid是否为空
        if (userId != null) {
            // 2 查询对应的实体
            Query query = Query.query(Criteria.where("refId").is(userId).and("type").is(ApBehaviorEntry.Type.USER.getCode()));
            ApBehaviorEntry userIdEntry = mongoTemplate.findOne(query, ApBehaviorEntry.class);
            // 判断实体类是否为空
            if (userIdEntry == null) {
                // 3 说明userid 对应的实体不存在 基于userId创建实体数据
                ApBehaviorEntry entry = new ApBehaviorEntry();
                entry.setRefId(userId);
                entry.setType(ApBehaviorEntry.Type.USER.getCode());
                mongoTemplate.save(entry);
                return entry;
            }
            return userIdEntry;
        }
        // 2 判断设备id是否为空
        if(equipmentId != null){
            // 2 查询对应的实体
            Query query = Query.query(Criteria.where("refId").is(equipmentId).and("type").is(ApBehaviorEntry.Type.EQUIPMENT.getCode()));
            ApBehaviorEntry equipmentIdEntry = mongoTemplate.findOne(query, ApBehaviorEntry.class);
            // 判断实体类是否为空
            if (equipmentIdEntry == null) {
                // 3 说明userid 对应的实体不存在 基于userId创建实体数据
                ApBehaviorEntry entry = new ApBehaviorEntry();
                entry.setRefId(equipmentId);
                entry.setType(ApBehaviorEntry.Type.EQUIPMENT.getCode());
                mongoTemplate.save(entry);
                return entry;
            }
            return equipmentIdEntry;
        }
        return null;
    }
}
